package com.yq.service.impl;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.google.common.collect.Maps;
import com.yq.core.entity.SysCorRolePowerEntity;
import com.yq.core.entity.SysCorUserRoleEntity;
import com.yq.core.entity.SysRoleEntity;
import com.yq.core.service.SysCorRolePowerService;
import com.yq.core.service.SysRoleService;
import com.yq.core.util.Page;
import com.yq.service.annotation.AzerothAutoService;
import com.yq.service.dao.BaseMapper;
import com.yq.service.dao.SysRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;


/**
 * 信  息: [yinquan] [2017-05-04] [1.0]
 * 描  述: Service 实现
 */
@AzerothAutoService("sysRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRoleEntity, String> implements SysRoleService {

    private static Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysCorRolePowerService sysCorRolePowerService;

    public BaseMapper<SysRoleEntity, String> getBaseMapper() {
        return sysRoleMapper;
    }

    /** 角色列表查询 **/
    public Page<Map<String, Object>> pageRoleList(Map<String, Object> parameter, Page page) {
        PageBounds pageBounds = new PageBounds(page.getPageCurrent(), page.getPageSize(), true);
        List<Map<String, Object>> list = sysRoleMapper.pageRoleList(parameter, pageBounds);
        PageList<Map<String, Object>> pageList = (PageList) list;
        page.setRows(pageList);
        page.setTotalPageNum(pageList.getPaginator().getTotalPages());// 总页数
        page.setTotal(pageList.getPaginator().getTotalCount());// 总记录数
        return page;
    }

    /** 所有角色列表查询 **/
    public List<Map<String, Object>> pageRoleAllList(Map<String, Object> parameter) {
        return sysRoleMapper.pageRoleAllList(parameter);
    }

    /** 角色授权 **/
    public void updateAccredit(Map<String, Object> parameter) {

        Map<String, Object> par = Maps.newHashMap();

        String powrUids = parameter.get("powrUids").toString();
        String roleUid = parameter.get("roleUid").toString();

        // 删除【角色 - 权限】关联数据
        par.put("roleUid", roleUid);
        sysCorRolePowerService.deleteAccredit(par);

        String[] uids = powrUids.split(",");

        for(String u:uids) {
            // 更新【角色 - 权限】关联表
            SysCorRolePowerEntity sysCorRolePowerEntity = new SysCorRolePowerEntity();
            sysCorRolePowerEntity.setRoleUid(roleUid);
            sysCorRolePowerEntity.setPowerUid(u);

            sysCorRolePowerService.insert(sysCorRolePowerEntity);

        }
    }

    /** 获取角色权限关联 **/
    public List<Map<String, Object>> rolePowerTree(Map<String, Object> parameter) {
        return sysRoleMapper.rolePowerTree(parameter);
    }

}